package cn.iocoder.yudao.module.indicator.domain.vo;

import cn.iocoder.yudao.module.indicator.domain.entity.Indicator;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description 指标计算返回值，集成指标信息实体，返回指标的基础信息
 * @Author ZWC
 * @Date 2024/9/26 14:20
 */
@Data
public class IndexCalculationVo extends Indicator {

    public static String INDEX_ERROR_NUMBER = "-";
    /**
     * 指标值,未达到计算条件统一给 `-`
     */
    private String indexNumber = INDEX_ERROR_NUMBER;

    /**
     * 存放元素明细
     */
    private List<ElementCalculationVo> elementCalculationVoList;

    /**
     * 上一期指标值
     */
    private DetailIndexCalculationVo lastPeriodIndex;
    /**
     * 同期指标值
     */
    private DetailIndexCalculationVo samePeriodIndex;

    /**
     * 同比指标值
     */
    private String tb;

    /**
     * 环比指标值
     */
    private String hb;

    /**
     * 元素id数组
     */
    private List<Long> elementIdList;

    public List<Long> getElementIdList() {
        String elementIds = super.getElementIds();
        if (!StringUtils.isEmpty(elementIds)) {
            //元素ids
            List<Long>  idsList  = Arrays.stream(elementIds.split(","))
                    .map(s -> Long.parseLong(s.trim()))
                    .collect(Collectors.toList());
            return  idsList.stream().distinct().collect(Collectors.toList());
        }
        return new ArrayList<>();
    }



    public String getHb() {
        if (lastPeriodIndex != null) {
            return calculatedGrowth(indexNumber, lastPeriodIndex.getIndexNumber());
        }
        return "";
    }
    public String getTb() {
        if (samePeriodIndex != null) {
            return calculatedGrowth(indexNumber, samePeriodIndex.getIndexNumber());
        }
        return "";
    }

    /**
     * 功能描述: 计算指标的同环比
     * @param:
     * @return:
     * @author: ZWC
     * @date: 2024/10/22
     */
    private String calculatedGrowth(String value, String OldValue) {
        if (!Objects.equals(OldValue,"0") && !Objects.equals(OldValue,INDEX_ERROR_NUMBER)) {
            if (Objects.equals(value,INDEX_ERROR_NUMBER) || StringUtils.isEmpty(value)) {
                value = "0";
            }
            double v = (Double.valueOf(value) - Double.valueOf(OldValue)) / Double.valueOf(OldValue);
            // 保留两位小数并转换为字符串
            return String.format("%.2f", v * 100) + "%";
        }
        return "-";
    }


}
